/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package nsip.util;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Observable;

/**
 * Manages a number of items in this history
 * @author nico.rehwaldt
 */
public class History<T> extends Observable implements Iterable<T> {

    private final LinkedList<T> values;

    /**
     * Creates a history with no start element
     */
    public History() {
        this(null);
    }

    /**
     * Creates a history with the given start element
     * @param item
     */
    public History(final T item) {
        this.values = new LinkedList<T>();

        if (item != null) {
            add(item);
        }
    }
    
    /**
     * Returns a iterator to iterate over the elements in this history,
     * starting from oldest to newest item.
     * 
     * @return
     */
    public Iterator<T> iterator() {
        return values.iterator();
    }

    /**
     * Returns the last n elements from this history
     * @param n
     * @return
     */
    public List<T> last(int n) {
        int end = Math.max(0, values.size() - 1);
        return values.subList(Math.max(0, end - n), end);
    }

    /**
     * Adds the specified item to this history
     * @param item
     */
    public void add(T item) {
        setChanged();
        notifyObservers(item);
        this.values.add(item);
    }

    /**
     * Returns the last (most current) item in this history or null if no
     * items are present so far.
     * 
     * @return
     */
    public T last() {
        return values.peekLast();
    }

    @Override
    public String toString() {
        return values.toString();
    }
}
